package com.gaodun.hk.common.config;

import com.gaodun.hk.common.response.BasicResponse;
import com.gaodun.hk.common.response.ServiceException;
import com.gaodun.hk.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;

/**
 * @author fengyamin
 * @date 2020/04/14
 **/
@Slf4j
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public BasicResponse handleUnProcessableException(MethodArgumentNotValidException e) {
        log.warn("参数校验失败", e);
        Iterator var2 = e.getBindingResult().getAllErrors().iterator();
        if (var2.hasNext()) {
            ObjectError error = (ObjectError) var2.next();
            return BasicResponse.create(StatusCode.BAD_PARAMETER.getCode(), error.getDefaultMessage(), e.getMessage());
        } else {
            return BasicResponse.create(StatusCode.BAD_PARAMETER.getCode(), StatusCode.BAD_PARAMETER.getMessage(), e.getMessage());
        }
    }

    @ExceptionHandler({ServiceException.class})
    @ResponseStatus(HttpStatus.OK)
    public BasicResponse handleUnProcessableException(ServiceException e) {
        log.warn("业务异常", e);
        return BasicResponse.create(StatusCode.FAILED.getCode(), e.getMessage(), e.getData());
    }

    @ExceptionHandler({Exception.class})
    public BasicResponse handleUnProcessableException(Exception e) {
        log.warn("异常", e);
        if (e instanceof IllegalArgumentException) {
            return BasicResponse.create(StatusCode.FAILED.getCode(), e.getMessage(), null);
        } else {
            return BasicResponse.create(StatusCode.FAILED.getCode(), "接口异常，请联系管理员！", e.getMessage());
        }
    }
}
